package com.rzjm.api.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.service.*;
import com.rzjm.api.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  企业相关
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/shop")//url:模块/资源/{}/细分
public class ShopController extends BaseController {

    @Resource
    private ShopService shopService;
    @Resource
    private ShopPostService shopPostService;
    @Resource
    private TempProjectService tempProjectService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private UserShopRelationService userShopRelationService;


    /**
     * 电焊机设备详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    @ResponseBody
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "shop/test： " + requestParam);
            System.out.println("company/test： " + requestParam);

            //企业信息上传
//            Platform platform = platformService.getById(2);
//            QueryWrapper<Company> qw = new QueryWrapper<>();
//            qw.eq("platform_id", 2);
//            qw.isNotNull("social_code");
//            List<Company> list = companyService.list(qw);
//            ElectricWeldingUtil.uploadCompany(list, platform);

            shopService.uploadData(5);


            //焊机信息上传
//            Company company = companyService.findById(1);
//            List<Device> deviceList = deviceService.selectListByColumn("id", 1);
////            ElectricWeldingUtil.uploadDevice(company,deviceList, platform);
//
//            //智能终端设备信息上传
////            ElectricWeldingUtil.uploadDeviceIot(company,deviceList, platform);
//
//
//            //焊工信息上报
//            QueryWrapper<SysUser> qwUser = new QueryWrapper<>();
//            qwUser.eq("user_id", 3);
//            List<SysUser> sysUserList = sysUserService.list(qwUser);
//            //焊工上传
////            ElectricWeldingUtil.uploadOperationInfo(company, sysUserList, platform);
//
//
//            // 焊工证上传
//            ElectricWeldingUtil.uploadCertificateInfo(company, sysUserList, platform, uploadPath);
//


            // 日志上报
//            String moduleCode = "";
//            SysUser sysUser = sysUserService.findById(3);
//            DeviceRecord record = deviceRecordService.findById(1);
//            if(record != null){
//                Device device = deviceService.findById(record.getDeviceId());
//                if(device != null){
//                    moduleCode = device.getFsrBreakerId();
//                }
////            company, record, moduleCode, status, sysUser, platform
////                ElectricWeldingUtil.uploadDeviceLog(company, record, moduleCode, "1", sysUser, platform);
//            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("device/detail",e);
        }
        return result;
    }

    /**
     * 企业详情信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/detail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;
            if(shop_id == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }
            Shop shop = shopService.findById(shop_id);
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }
            map.put("shop",shop);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/detail",e);
        }
        return result;
    }

    /**
     * 企业详情信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/detailByNo",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject detailByNo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String shop_no = jsonRequest.containsKey("shop_no") ? jsonRequest.getStr("shop_no") : null;

            QueryWrapper<Shop> qw = new QueryWrapper<>();
            qw.eq("shop_no",shop_no);
            qw.last("limit 1");
            Shop shop = shopService.getOne(qw);
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }
            map.put("shop",shop);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/detail",e);
        }
        return result;
    }

    /**
     * 企业信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/shopinfo",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject shopinfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String num = jsonRequest.containsKey("num") ? jsonRequest.get("num").toString() : "";
            String op_type = jsonRequest.containsKey("op_type") ? jsonRequest.getStr("op_type") : "terminal";
            int is_clean = jsonRequest.containsKey("isclean") ? jsonRequest.getInt("isclean") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 1;
            if(shop_id == 0){
                shop_id = 1;
            }

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }
            int t_shop_id = 0;
            Shop shop = null;
            if(op_type.equals("terminal")){
                QueryWrapper<CkTerminal> qw1 = new QueryWrapper<CkTerminal>();
                qw1.eq("shop_id",shop_id);
                qw1.eq("terminal_num",num);
                CkTerminal terminal = ckTerminalService.getOne(qw1);
                if(terminal == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该终端不存在"),true,true);
                }
                t_shop_id = terminal.getShopId();
                if(terminal.getIsHealth() == 1){//如果是 保养设备
                    if(is_clean == 0 || is_clean == 1){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备无需进行该操作"),true,true);
                    }
                }else if(terminal.getIsHealth() == 0){//巡检  清理设备
                    if(is_clean == 2){//如果扫码保养
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备无需进行该操作"),true,true);
                    }
                }
                shop = shopService.selectById(terminal.getShopId());
            }else if(op_type.equals("post")){
                ShopPost shopPost = shopPostService.selectByUniqueColumn("post_num",num);
                if(shopPost!=null){
                    shop = shopService.selectById(shopPost.getShopId());
                    t_shop_id = shopPost.getShopId();
                }
            }else if(op_type.equals("tempro")){
                TempProject tempProject = tempProjectService.selectByUniqueColumn("project_num",num);
                if(tempProject!=null){
                    shop = shopService.selectById(tempProject.getShopId());
                    t_shop_id = tempProject.getShopId();
                }
            }

            if(sysUser.getUserType() >= 4){
                if(sysUser.getShopId() != t_shop_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该没有该企业权限"),true,true);
                }
            }else{
                QueryWrapper<UserShopRelation> qw = new QueryWrapper<>();
                qw.eq("sys_user_id",sysUser.getUserId());
                qw.eq("shop_id",t_shop_id);
                UserShopRelation relation = userShopRelationService.getOne(qw);
                if(relation == null){
                    if(sysUser.getShopId() != t_shop_id){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该没有该企业权限"),true,true);
                    }
                }
            }


            if(shop!=null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",shop),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"关联的商户不存在",shop),true,false);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/shopinfo",e);
        }
        return result;
    }

    /**
     * 企业列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/list",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;

            int offset = (pageindex - 1) * pagesize;

            List<Shop> list = shopService.selectByState(1,shop_type,offset,pagesize,longitude,latitude);
            map.put("shops",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/list",e);
        }
        return result;
    }

    /**
     *   我的企业列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/my/list",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject myList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 1;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;
            int device_type = jsonRequest.containsKey("device_type") ? jsonRequest.getInt("device_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : "";
            int position = jsonRequest.containsKey("position") ? jsonRequest.getInt("position") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.getSysUserByUser(user);
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }


            if(shop_type == 4 || shop_type == 9 || shop_type == 10){
                //制粒机模块
                if(sysUser.getIsOpenZhili() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"模块未开启"),true,true);
                }
            }else if(shop_type == 5){
                //筒仓测量模块
                if(sysUser.getIsOpenRange() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"模块未开启"),true,true);
                }
            }


            if(sysUser.getStatus() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"用户已禁用"),true,true);
            }

            List<Shop> list = shopService.selectMyList(user,1, keyword, shop_type, device_type,position, pageIndex, pageSize);
            map.put("shops",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/list",e);
        }
        return result;
    }

    /**
     * 搜索的企业列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/searchlist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject searchlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String key_word = jsonRequest.containsKey("key_word") ? jsonRequest.getStr("key_word") : "";
            int pageindex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pagesize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;

            int offset = (pageindex - 1) * pagesize;

            List<Shop> list = shopService.selectBySearch(key_word,shop_type,1,offset,pagesize,longitude,latitude);
//            map.put("shops",list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/searchlist",e);
        }
        return result;
    }

    /**
     * 获取企业列表下拉框数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/shoplist",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject shoplist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int groupId = jsonRequest.containsKey("group_id") ? jsonRequest.getInt("group_id") : -1;

            QueryWrapper<Shop> qw = new QueryWrapper<>();
            qw.eq("state", 1);
            if (groupId != -1){
                qw.eq("group_id", groupId);
            }
            List<Shop> list = shopService.list(qw);
//            map.put("shops",list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("shop/shoplist",e);
        }
        return result;
    }
}
